import { watch, ref } from 'vue';
import { isEmpty } from 'lodash';

/**
 * 1. 当场馆加载后，自动轮播场馆；
 * 2. 当切换场馆筛选变化时，如果是全部则重新轮播，如果选中当前场馆，则只选中场馆；
 * 3. 当手动选中某个场馆时，轮播停止；点击继续轮播，从当前选中的场馆继续轮播；
 */
const useLoop = ({ fullMarkMap, filterValue }) => {
  let init = false;
  let loop = null;
  let index = 0;
  const timestamp = 3000;

  // 当前选中的场馆id
  const activePointId = ref(null);

  /**
   * 执行轮播
   */
  function goRun() {
    if (!isEmpty(fullMarkMap)) {
      const keys = Object.keys(fullMarkMap);
      console.log('goRun come in', keys);
      activePointId.value = keys[index];
      if (index >= keys.length - 1) {
        index = 0;
      } else {
        index++;
      }
      loop = setTimeout(goRun, timestamp);
    }
  }

  /**
   * 选中Mark
   * @param {*} mark
   */
  function chooseMark(mark) {
    clearTimeout(loop);
    activePointId.value = mark.id;
  }

  /**
   * 过滤切换时触发的事件
   */
  watch(
    () => filterValue.value,
    (filter) => {
      if (!isEmpty(filter)) {
        const mark = fullMarkMap[filter];
        console.log(filter, mark);
        chooseMark(mark);
      } else {
        goRun();
      }
    },
    {
      immediate: true,
    }
  );

  return {
    chooseMark,
    goRun,
    init,
    activePointId,
  };
};

export default useLoop;
